package com.rfid.analysis;

import android.util.Log;

import java.nio.ByteBuffer;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;

/**
 * @author Administrator
 * @date 2020/9/17
 */
public class HandlerCRC extends Handler {
    @Override
    public void handleRequest(Message request) {
        if(logOpen) {
            Log.e("handleRequest", "进入HandlerCRC");
        }
        request.setCurrentNodeHandler(this);
        ByteBuffer byteBuffer = request.getBuffer();
        if (byteBuffer.position() + getLength() <= byteBuffer.limit()) {
            byte[] read = new byte[getLength()];
            byteBuffer.get(read);
            String crcData = CRC16(listToByte(request.getAllData()));
            if(logOpen) {
                Log.e("handleRequest", "计算的CRC=" + crcData);
            }
            byte[] hexCrc = hexStringToBytes(crcData);

            if (Arrays.equals(hexCrc, read)) {
                //验证成功
                request.addData(read);
                request.setHasComplete(true);
                if (getNext() != null) {
                    getNext().handleRequest(request);
                }
            } else {
                //验证失败，数据丢弃
                request.getFirstHandler().handleRequest(request);
            }
        } else {
            byteBuffer.compact();
        }
    }

    private byte[] listToByte(List<Byte> list) {
        if (list == null)
            return null;
        byte[] bytes = new byte[list.size()];
        int i = 0;
        Iterator<Byte> iterator = list.iterator();
        while (iterator.hasNext()) {
            bytes[i] = iterator.next();
            i++;
        }
        return bytes;
    }

    public byte[] hexStringToBytes(String hexString) {
        if (hexString == null || hexString.equals("")) {
            return null;
        }
        hexString = hexString.toUpperCase();
        int length = hexString.length() / 2;
        char[] hexChars = hexString.toCharArray();
        byte[] d = new byte[length];
        for (int i = 0; i < length; i++) {
            int pos = i * 2;
            d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
        }
        return d;
    }

    private byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public int getLength() {
        return 2;
    }

    public byte checkSum(List<Byte> data) {
        byte crc = 0;

        for (int i = 1; i < data.size(); ++i) {
            crc += data.get(i);
        }

        return crc;
    }

    private String CRC16(byte[] data) {
        int CRC_POLYNOM = 0xA001; // 多项式：X16 + X12 + X5 + 1 -> CRC_POLYNOM = 0x8408;
        int CRC_PRESET = 0xFFFF; // 初始值：0xFFFF -> CRC_PRESET = 0xFFFF;
        int crc = CRC_PRESET;
        int cnt = data.length;
        for (int i = 0; i < cnt; i++) // cnt – 协议数据长度（不包含CRC和开始位）
        {
            crc ^= data[i] & 0xff;
            for (int j = 0; j < 8; j++) {
                if ((crc & 0x0001) != 0)
                    crc = ((crc >> 1) ^ CRC_POLYNOM);
                else
                    crc = (crc >> 1);
            }
        }
        String crcHex = Integer.toHexString(crc).toUpperCase();
        crcHex = "0000".substring(0, 4 - crcHex.length()) + crcHex;
        return crcHex.substring(2) + crcHex.substring(0, 2);
    }
}